package com.property.manage.service.renovation;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guardchina.framework.mybatis.model.CustomPage;
import com.guardchina.framework.util.exception.BusinessException;
import com.guardchina.framework.util.utils.PhoneUtil;
import com.property.manage.dao.renovation.DepositMapper;
import com.property.manage.model.flowingWater.TotalVo;
import com.property.manage.model.renovation.DepositEntity;
import com.property.manage.model.renovation.DepositVo;
import com.property.manage.service.flowingWater.FlowingWaterService;
import com.property.manage.service.system.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述
 *
 * @author lwb
 * @since 2020/7/15
 */
@Component
@Slf4j
public class DepositService {
    @Autowired
    private DepositMapper depositMapper;
    @Value("${timed.patee}")
    private String patee;
    @Autowired
    private FlowingWaterService flowingWaterService;
    @Autowired
    private RenovationService renovationService;
    @Autowired
    private UserService userService;

    public CustomPage<DepositVo> page(Long pageNo, Long pageSize, String payer, Integer villageId, Integer type) {
        Page<DepositVo> page = new Page<>(pageNo, pageSize);
        IPage<DepositVo> village = depositMapper.getPage(page, payer, villageId, type);
        return new CustomPage<>(village);
    }


    public void add(BigDecimal money, String payer,
                    String phone, Integer buildingId, Integer renovationId, Integer villageId, Integer type,
                    Integer userId, Integer printing
    ) {

        if (!PhoneUtil.isMobile(phone)) {
            throw new BusinessException("请填写正确的手机号码", String.format("手机号码错误[%s]", phone));
        }
        DepositEntity entity = new DepositEntity();
        entity.setMoney(money);
        entity.setBuildingId(buildingId);
        entity.setPatee(patee);
        entity.setPayer(payer);
        entity.setPhone(phone);
        entity.setRenovationId(renovationId);
        entity.setStatus(1);
        entity.setTime(LocalDate.now());
        entity.setVillageId(villageId);
        entity.setType(type);
        entity.setDrawer(userService.findUser(userId).getUserName());
        //判断是否打印票据
        depositMapper.insert(entity);
    }

    public void update(Integer id, BigDecimal money, String payer,
                       String phone, Integer buildingId, Integer villageId
    ) {
        UpdateWrapper<DepositEntity> wrapper = new UpdateWrapper<>();
        wrapper.set("money", money);
        wrapper.set("payer", payer);
        wrapper.set("phone", phone);
        wrapper.set("village_id", villageId);
        wrapper.set("building_id", buildingId);
        wrapper.eq("renovation_id", id);
        depositMapper.update(null, wrapper);
    }

    public void update(Integer id, BigDecimal refund, Integer status, Integer userId
    ) {
        UpdateWrapper<DepositEntity> wrapper = new UpdateWrapper<>();
        wrapper.set("status", status);

        if (status == 3) {
            DepositEntity byId = this.getById(id);
            if (byId == null || !"2".equals(byId.getStatus())) {
                throw new BusinessException("未缴纳押金或已经完成退费", String.format("id:[%S]", id));
            }
            wrapper.set("refund", refund);
            wrapper.set("return_time", LocalDate.now());
            wrapper.set("return_name", userService.findUser(userId).getUserName());
        }
        wrapper.eq("id", id);
        depositMapper.update(null, wrapper);
    }


    public void delete(Integer id) {
        depositMapper.deleteById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public void deposit(Integer id, Integer userId, Integer printing) {
        try {
            DepositEntity entity = depositMapper.selectById(id);
            if (entity == null) {
                throw new BusinessException("id错误", String.format("id:[%S]", id));
            }
            //判断是否打印
            //flowingWaterService.add(id, entity.getMoney(), null, SysSet.DEPOSIT_NAME, 4, entity.getPayer(), patee, 1, LocalDate.now(), "1", entity.getVillageId(),entity.getBuildingId(),userId);
            this.update(id, null, 2, userId);
            renovationService.updatStatus(entity.getRenovationId(), 2);
        } catch (Exception e) {
            throw new BusinessException("缴费失败", String.format("缴费失败[%S]", e));
        }

    }

    @Transactional(rollbackFor = Exception.class)
    public void refund(Integer id, BigDecimal refund, Integer userId) {
        try {
            DepositEntity entity = depositMapper.selectById(id);
            if (entity == null) {
                throw new BusinessException("id错误", String.format("id:[%S]", id));
            }
            // flowingWaterService.add(id, refund, null, SysSet.REFUND_NAME, 5, patee, entity.getPayer(), 2, LocalDate.now(), "1", entity.getVillageId(),entity.getBuildingId(),userId);
            this.update(id, refund, 3, userId);
            renovationService.updatStatus(entity.getRenovationId(), 3);
        } catch (Exception e) {
            throw new BusinessException("退费失败", String.format("退费失败[%S]", e));
        }
    }

    public DepositEntity getById(Integer id) {
        return depositMapper.selectById(id);
    }

    public BigDecimal getMoney(String startTime, String endTime, Integer villageId, Integer type) {
        BigDecimal money = depositMapper.getMoney(startTime, endTime, villageId, type);
        if (money == null) {
            return new BigDecimal(0);
        }
        return money;
    }

    public BigDecimal getMoneyDetailed(String startTime) {
        BigDecimal money = depositMapper.getMoneyDetailed(startTime);
        if (money == null) {
            return new BigDecimal(0);
        }
        return money;
    }

    public BigDecimal getRefund(String startTime, String endTime, Integer villageId, Integer type) {
        BigDecimal money = depositMapper.getRefund(startTime, endTime, villageId, type);
        if (money == null) {
            return new BigDecimal(0);
        }
        return money;
    }

    public BigDecimal getRefundDetailed(String startTime) {
        BigDecimal money = depositMapper.getRefundDetailed(startTime);
        if (money == null) {
            return new BigDecimal(0);
        }
        return money;
    }

    public List<String> findTime(String startTime, String endTime) {
        List<String> strings = depositMapper.selectTime(startTime, endTime);
        List<String> list = depositMapper.selectRefundTime(startTime, endTime);
        if (strings.isEmpty() && list.isEmpty()) {
            return Collections.emptyList();
        }
        strings.addAll(list);
        //去重复
        List<String> collect = strings.stream().distinct().collect(Collectors.toList());
        Collections.reverse(collect);
        return collect;
    }

    public List<Integer> selectBuildingId(String startTime, String endTime, Integer villageId) {
        return depositMapper.selectBuildingId(startTime, endTime, villageId);
    }

    public TotalVo getMoneyByBuildingId(String startTime, String endTime, List<Integer> ids) {
        return depositMapper.getMoneyByBuildingId(startTime, endTime, ids);
    }

    public TotalVo getRefundByBuildingId(String startTime, String endTime, List<Integer> ids) {
        return depositMapper.getRefundByBuildingId(startTime, endTime, ids);
    }
}
